package com.student.education.service.impl;

import com.student.education.entity.CheckWorkType;
import com.student.education.dao.CheckWorkTypeDao;
import com.student.education.service.CheckWorkTypeService;
import com.student.education.to.CheckWorkTypeQueryTo;
import com.student.education.vo.CheckWorkTypeQueryVo;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 考勤类型表(CheckWorkType)表服务实现类
 *
 * @author makejava
 * @since 2021-10-09 23:40:03
 */
@Service("checkWorkTypeService")
public class CheckWorkTypeServiceImpl implements CheckWorkTypeService {
    @Resource
    private CheckWorkTypeDao checkWorkTypeDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public CheckWorkType queryById(Integer id) {
        return this.checkWorkTypeDao.queryById(id);
    }

    /**
     * 新增数据
     *
     * @param checkWorkType 实例对象
     * @return 实例对象
     */
    @Override
    public int insert(CheckWorkType checkWorkType) {
        return this.checkWorkTypeDao.insert(checkWorkType);
    }

    /**
     * 修改数据
     *
     * @param
     * @return 实例对象
     */
    @Override
    public int update(Integer id,String name) {
        return this.checkWorkTypeDao.update(id,name);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.checkWorkTypeDao.deleteById(id) > 0;
    }

    @Override
    public List<CheckWorkTypeQueryTo> queryAll() {
        List<CheckWorkTypeQueryTo> list = checkWorkTypeDao.queryAll();
        return toTree(list,0);
    }

    public static List<CheckWorkTypeQueryTo> toTree(List<CheckWorkTypeQueryTo> treeList, Integer pid) {
        List<CheckWorkTypeQueryTo> retList = new ArrayList<>();
        for (CheckWorkTypeQueryTo parent : treeList) {
            if (pid.equals(parent.getPid())) {
                retList.add(findChildren(parent, treeList));
            }
        }
        return retList;
    }
    private static CheckWorkTypeQueryTo findChildren(CheckWorkTypeQueryTo parent, List<CheckWorkTypeQueryTo> treeList) {
        for (CheckWorkTypeQueryTo child : treeList) {
            if (parent.getId().equals(child.getPid())) {
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(findChildren(child, treeList));
            }
        }
        return parent;
    }
}
